<template>
  <u-count-down
    ref="countDown"
    :time="timeLeft"
    format="DD:HH:mm:ss"
    :autoStart="true"
    @change="onCountDownChange"
  >
    <view class="time">
      <view class="time__custom">
        <text class="time__custom__item">{{
          timeData.days > 9 ? timeData.days : "0" + timeData.days
        }}</text>
      </view>
      <text class="time__doc">:</text>
      <view class="time__custom">
        <text class="time__custom__item">{{
          timeData.hours > 9 ? timeData.hours : "0" + timeData.hours
        }}</text>
      </view>
      <text class="time__doc">:</text>
      <view class="time__custom">
        <text class="time__custom__item">{{
          timeData.minutes > 9 ? timeData.minutes : "0" + timeData.minutes
        }}</text>
      </view>
      <text class="time__doc">:</text>
      <view class="time__custom">
        <text class="time__custom__item">{{
          timeData.seconds > 9 ? timeData.seconds : "0" + timeData.seconds
        }}</text>
      </view>
    </view>
  </u-count-down>
</template>
<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import dayjs from "dayjs";

const props = defineProps({
  endTime: {
    type: String,
    default: "",
  },
});

const timeData = ref({
  days: 0,
  hours: 0,
  minutes: 0,
  seconds: 0,
});

const timeLeft = ref(0); // 添加：剩余时间的响应式变量

watch(
  () => props.endTime,
  (val) => {
    const left = timeDataFilter(val);
    timeLeft.value = left; // 更新剩余时间
    const dayjsTime = dayjs(left);
    timeData.value = {
      days: dayjsTime.get("dates"),
      hours: dayjsTime.get("hours"),
      minutes: dayjsTime.get("minutes"),
      seconds: dayjsTime.get("seconds"),
    };
  },
  {
    immediate: true,
  }
);

function timeDataFilter(endTime) {
  const end_time_2 = endTime.split("-");
  const new_end_time = end_time_2.join("/");
  const start = Date.now();
  const end = new Date(new_end_time).getTime();
  return end - start;
}

function onCountDownChange(e) {
  timeData.value = e;
}
</script>

<style lang="scss" scoped>
.time {
  @include flex;
  align-items: center;

  &__custom {
    width: 22px;
    height: 22px;
    background-color: #ff0000;
    border-radius: 4px;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
    align-items: center;

    &__item {
      color: #fff;
      font-size: 12px;
      text-align: center;
    }
  }

  &__doc {
    color: #ff0000;
    padding: 0px 4px;
  }

  &__item {
    color: #606266;
    font-size: 15px;
    margin-right: 4px;
  }
}
</style>
